package cn.itsource.basic.exception;

import cn.itsource.basic.util.AjaxResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice //对所有添加了RequestMapping的类做增强
public class GlobalExceptionHandler {

    /**
     * 当加了RequestMapping的类中
     * 出现了CustomException
     * 就执行下面对应的方法
     */
    @ExceptionHandler(CustomException.class)
    public AjaxResult CustomExceptionHandle(CustomException e){
        e.printStackTrace();
        //获取异常的message，其实就是错误代码
        String code = e.getMessage();
        //通过错误代码获取错误代码对应的错误信息
        String msg = ErrorCode.getMessageByCode(code);
        return AjaxResult.me().setSuccess(false).setCode(Integer.valueOf(e.getMessage())).setMessage(msg);
    }


    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandle(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setCode(1001).setSuccess(false).setMessage("系统繁忙");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult validExceptionHandle(MethodArgumentNotValidException e){
        e.printStackTrace();
        return AjaxResult.me().setCode(1002).setSuccess(false).setMessage("参数错误");
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public AjaxResult paramExceptionHandle(ConstraintViolationException e){
        e.printStackTrace();
        return AjaxResult.me().setCode(1002).setSuccess(false).setMessage("参数错误");
    }
}
